﻿using System;
using WindowsPhoneEssentials.Storage;

namespace WindowsPhoneMvp.Phone.State
{
    ///<summary>
    /// Provides access to a page's transient state
    ///</summary>
    public sealed class PageTransientStateStore : IStorageProvider
    {
        private readonly WeakReference phoneApplicationPage;

        ISupportsState Page
        {
            get
            {
                return ((ISupportsState) phoneApplicationPage.Target);
            }
        }

        ///<summary>
        /// Creates a new PageTransientStateStore
        ///</summary>
        internal PageTransientStateStore(ISupportsState phoneApplicationPage)
        {
            if (phoneApplicationPage == null) throw new ArgumentNullException("phoneApplicationPage");
            this.phoneApplicationPage = new WeakReference(phoneApplicationPage);
        }

        public void Save<T>(string key, T value)  where T : class
        {
            Page.State[key] = value;
        }

        public T Load<T>(string key)  where T : class
        {
            object value;
            if(Page.State.TryGetValue(key, out value))
                return (T)value;
            return default(T);
        }

        public bool Contains(string key)
        {
            return Page.State.ContainsKey(key);
        }

        public void Remove(string key)
        {
            if(Page.State.ContainsKey(key))
                Page.State.Remove(key);
        }
    }
}
